package org.bpms.service.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.bpms.model.admin.Suser;
import org.bpms.util.Encrypt;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 后台用户业务处理
 * @author hupei
 * @Before(Tx.class)事务拦截
 */
public class UserService {
	
	/**
	 * 保存用户
	 * @param user
	 * @return
	 */
	@Before(Tx.class)
	public Suser saveOrUpdate(Suser user){
		if (null != user.getStr("password") && !user.getStr("password").equals("")){
			user.set("password", user.getStr("password"));
		}
		if (null != user.getStr("id")){
			user.update();
		}else{
			user.set("id", UUID.randomUUID().toString().replaceAll("-", ""));
			user.save();
		}
		return user;
	}
	
	/**
	 * 查找所有用户
	 * @param code
	 * @param realname
	 * @param pageNumber
	 * @param pageSize
	 * @param orderField
	 * @param orderDirection
	 * @param pagemap
	 */
	public void findAll(String code,String realname,Integer pageNumber,Integer pageSize,
	           String orderField,String orderDirection,Map<String,Object> pagemap){
		StringBuffer sql = new StringBuffer("from suser a left join suser b on a.leader=b.id where 1=1 ");
		if (null != code){
			sql.append(" and a.code like '%"+code+"%'");
		}
		if (null != realname){
			sql.append(" and a.realname like '%"+realname+"%'");
		}		
		sql.append(" order by a."+orderField+" "+orderDirection);
		Page<Suser> rolePage = Suser.me.paginate(pageNumber, pageSize, "select a.*,b.realname as leadername", sql.toString());
		pagemap.put("pageSize", rolePage.getPageSize());//页面大小
		pagemap.put("totalRow", rolePage.getTotalRow());//总行数
		pagemap.put("pageCurrent", rolePage.getPageNumber());//当前页号
		pagemap.put("orderField", orderField);//排序列名
		pagemap.put("orderDirection", orderDirection);//排序方式
		pagemap.put("pageData", rolePage.getList());//页面数据
	}
	
	/**
	 * 获取属于角色的用户
	 * @param roleid
	 * @return
	 */
	public List<Suser> userFromRole(String roleid){
		List<Suser> susers = new ArrayList<Suser>();
		susers = Suser.me.find("select a.id , a.username , a.realname , "
				+ "case when b.rid is null then 'false' else 'true' end as checked "
				+ "from suser a left join suserrole b on a.id=b.uid and b.rid=?" , roleid);
		return susers;
	}
	
	/**
	 * 获取属于部门的用户
	 * @param deptid
	 * @return
	 */
	public List<Suser> userFromDept(String deptid){
		List<Suser> susers = new ArrayList<Suser>();
		susers = Suser.me.find("select a.id , a.username , a.realname , "
				+ "case when b.did is null then 'false' else 'true' end as checked "
				+ "from suser a left join sdeptuser b on a.id=b.uid and b.did=?" , deptid);
		return susers;
	}
	
	/**
	 * 获取属于类型的用户
	 * @param deptid
	 * @return
	 */
	public List<Suser> userFromType(String typeid){
		List<Suser> susers = new ArrayList<Suser>();
		susers = Suser.me.find("select a.id , a.username , a.realname , "
				+ "case when b.tid is null then 'false' else 'true' end as checked "
				+ "from suser a left join typeuser b on a.id=b.uid and b.tid=?" , typeid);
		return susers;
	}
	
	/**
	 * 删除用户
	 * @param userId
	 */
	@Before(Tx.class)
	public void delUser(String userId){
		//删除该用户拥有的菜单关联
		Db.update("delete from suserrole where uid=?" , userId);
		Db.update("update suser set leader=null where leader=?" , userId);
		Db.update("update sdept set leader=null where leader=?" , userId);
		Suser.me.deleteById(userId);
	}
	
	/**
	 * 查找用户
	 * @param userId
	 * @return
	 */
	public Suser findById(String userId){
		String sql = "select a.*,b.realname as leadername "
				+ "from suser a left join suser b on a.leader=b.id where a.id=?";
		List<Suser> ls = Suser.me.find(sql , userId);
		if (null != ls && ls.size() > 0){
			return ls.get(0);
		}
		return null;
	}
	
	/**
	 * 新增用户时，查找有无同用户名的账户
	 * @param username
	 * @return
	 */
	public Suser findByUsername(String username){
		String sql = "select * "
				+ "from suser where username=?";
		List<Suser> ls = Suser.me.find(sql , username);
		if (null != ls && ls.size() > 0){
			return ls.get(0);
		}
		return null;		
	}
	
	/**
	 * 登陆验证
	 * @param username
	 * @param password
	 * @return
	 */
	public Suser login(String username , String password){
		List<Suser> user = Suser.me.find("select * from suser t where "
				+ "binary t.username=? and binary t.password=?", username , password);
		if (null != user && user.size() > 0)
			return user.get(0);
		else
			return null;
	}
	
	/**
	 * 构建用户流程的oprate
	 * @param id 用户id
	 * @return
	 */
	public List<String> selectGroupById(String id){
		List<String> group = new ArrayList<String>();
		Suser user = Suser.me.findById(id);
		if (null != user){//加入用户名和真实姓名
			group.add(user.getStr("username"));
			if (null != user.getStr("realname"))
				group.add("realname");
			
			List<Record> depts = Db.find("select * from sdept where id in"
					+ "(select did from sdeptuser where uid=?)",id);
			for (Record re : depts){//加入部门
				group.add(re.getStr("text"));
			}
			
			List<Record> roles = Db.find("select * from srole where id in"
					+ "(select rid from suserrole where uid=?)",id);
			for (Record re : roles){//加入角色
				group.add(re.getStr("text"));
			}
		}
		
		return group;
	}
	
	/**
	 * 构建用户流程的oprate
	 * @param username 用户名
	 * @return
	 */
	public List<String> selectGroupByUsername(String username){
		List<String> group = new ArrayList<String>();
		Suser user =null;
		List<Suser> ls = Suser.me.find("select * from suser where username=?" , username);
		if (null != ls && ls.size() > 0){
			user = ls.get(0);
		}
		if (null != user){//加入用户名和真实姓名
			group.add(user.getStr("username"));
			if (null != user.getStr("realname"))
				group.add("realname");
			
			List<Record> depts = Db.find("select * from sdept where id in"
					+ "(select did from sdeptuser where uid=?)",user.getStr("id"));
			for (Record re : depts){//加入部门
				group.add(re.getStr("text"));
			}
			
			List<Record> roles = Db.find("select * from srole where id in"
					+ "(select rid from suserrole where uid=?)",user.getStr("id"));
			for (Record re : roles){//加入角色
				group.add(re.getStr("text"));
			}
		}
		return group;
	}
}
